package com.ldl.customize.service.admin;

import com.ldl.customize.dao.CityMapper;
import com.ldl.customize.dao.ProvinceMapper;
import com.ldl.customize.entity.Province;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;

/**
 * 功能描述:后台功能Service
 * 作者: LDL
 * 创建时间: 2014/5/9 16:37
 */
@Service
public class AdminService {
    public static final Logger logger;

    static {
        logger = LoggerFactory.getLogger(AdminService.class);
    }

    @Autowired(required = false)
    private ProvinceMapper provinceMapper;

    @Autowired(required = false)
    private CityMapper cityMapper;
    /**
     * 获取省级单位代码并保存信息
     * @return
     */
    private ArrayList<String> getAndSaveProvinceCodes() {
        ArrayList<String> provinceCodes = new ArrayList<String>();
        ArrayList<Province> provinces = new ArrayList<Province>();
        HttpClient httpClient = new HttpClient();
        GetMethod getMethod = new GetMethod("http://www.weather.com.cn/data/list3/city.xml");
        //设置成了默认的恢复策略，在发生异常时候将自动重试3次
        getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
        //执行Method
        try {
            int statusCode = httpClient.executeMethod(getMethod);
            if (statusCode != HttpStatus.SC_OK) {
                logger.debug("请求失败:" + getMethod.getStatusLine());
            }
            byte[] responseBody = getMethod.getResponseBody();
            String result = new String(responseBody);
            logger.debug(result);
            String[] results = result.split(",");
            String[] citys;

            for (String city : results) {
                Province p = new Province();
                citys = city.split("\\|");
                provinceCodes.add(citys[0]);
                p.setProvinceCode(citys[0]);
                p.setProvinceName(citys[1]);
                provinces.add(p);
            }
            saveProvinceCodes(provinces);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            getMethod.releaseConnection();
        }
        return provinceCodes;
    }

    /**
     * 保存省级单位代码
     * @param provinces
     */
    public void saveProvinceCodes(ArrayList<Province> provinces){

        for(Province province : provinces){


        }
    }
}
